use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::time::sleep;

// 防抖函数
fn debounce<F>(delay: Duration, f: F) -> impl FnMut()
where
    F: Fn() + Send + Sync + 'static,
{
    // 使用 Arc 共享闭包
    let f = Arc::new(f);
    let last_time = Arc::new(Mutex::new(None));

    // 返回一个闭包，用于触发防抖函数
    move || {
        let f = Arc::clone(&f);
        let last_time = Arc::clone(&last_time);

        tokio::spawn(async move {
            // 更新触发时间
            let now = tokio::time::Instant::now();
            *last_time.lock().unwrap() = Some(now);

            // 等待 delay 时间
            sleep(delay).await;

            // 检查是否是最新的触发
            if let Some(time) = *last_time.lock().unwrap() {
                if time == now {
                    f();
                }
            }
        });
    }
}

#[tokio::main]
async fn main() {
    // 创建一个防抖函数，延迟 500ms
    let mut debounced_print = debounce(Duration::from_millis(500), || {
        println!("Debounced: Hello, world!");
    });

    // 模拟高频触发
    for i in 0..10 {
        println!("Trigger: {}", i);
        debounced_print();
        tokio::time::sleep(Duration::from_millis(100)).await;
    }

    // 等待防抖函数执行
    tokio::time::sleep(Duration::from_secs(1)).await;
}